package cn.witque.service.impl;

import cn.witque.dao.ItripUserMapper;
import cn.witque.pojo.ItripUser;
import cn.witque.pojo.dto.Dto;
import cn.witque.service.TokenSevice;
import cn.witque.service.UserService;
import cn.witque.utils.DtoUtil;
import cn.witque.utils.Md5Util;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class
UserServiceImpl implements UserService {

    @Resource
    private  ItripUserMapper itripUserMapper;

    @Resource
    private SimpleMailMessage simpleMailMessage;

    @Resource
    private MailSender mailSender;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    SmsSingleSender ssender;


    /**
     * 用户注册方法
     * @param record
     * @return
     */
    @Override
    public Dto registUser(ItripUser record) {
        record.setUserPassword(Md5Util.getMd5(record.getUserPassword(),24));
        if (this.isRegist(record.getUserCode())) {
            return DtoUtil.getFailed("注册失败,用户名已经存在！", "109");
        }else if (itripUserMapper.insertSelective(record) < 0) {
            return DtoUtil.getFailed("注册失败", "101");
        }

        ItripUser user = itripUserMapper.selectActiveByUserCode(record.getUserCode());
        user.setUserType(0);
        user.setFlatID(user.getId());
        if (itripUserMapper.updateByPrimaryKeySelective(user) < 1){
            return DtoUtil.getFailed("出现错误,请联系后台管理员！","108");
        }
        return DtoUtil.getSuccess("注册成功");
    }


    /**
     * 短信验证码激活
     * @param phoneNum
     * @return
     * @throws HTTPException
     * @throws IOException
     */
    @Override
    public Dto sendPhoneMsg(String phoneNum) throws HTTPException, IOException {
        if (isActive(phoneNum)) {
            return DtoUtil.getFailed("您的账号已经激活，请勿重新激活","102");
        }
        //验证码生成
        Random random = new Random();
        String code = random.nextInt(900000) + 100000 +"";
        //手机号
        String[] phoneNumbers = {phoneNum};
        //短信模板
        int templateId = 178075;
        String[] params = {code,"30"};
        SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumbers[0],
                templateId, params, "", "", "");
        redisTemplate.opsForValue().set("active:"+phoneNum,code, 30, TimeUnit.MINUTES);
        return DtoUtil.getSuccess("激活码发送成功，有效期30分钟，请尽快激活！");
    }

    @Override
    public boolean isRegist(String userName) {
        ItripUser user = itripUserMapper.selectActiveByUserCode(userName);
        if (null != user){
            return true;
        }
        return false;
    }


    /**
     * 发送邮件方法
     * @param mailAddress
     * @return
     */
    @Override
    public Dto sendMail(String mailAddress){
        if (isActive(mailAddress)) {
            return DtoUtil.getFailed("您的账号已经激活，请勿重新激活","102");
        }
        String code = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("active:"+mailAddress, code, 30, TimeUnit.MINUTES);
        simpleMailMessage.setTo(mailAddress);
        simpleMailMessage.setText("你的激活码是：" + code);
        mailSender.send(simpleMailMessage);
        return DtoUtil.getSuccess("激活码发送成功，有效期30分钟，请尽快激活！");

    }

    /**
     * 登录方法根据用户名密码
     * @param userCode
     * @param passWord
     * @return
     */
    @Override
    public ItripUser Login(String userCode, String passWord) {
        ItripUser user = itripUserMapper.selectActiveByUserCode(userCode);
        return user;
    }



    /**
     * 根据缓存中的激活码激活指定用户名的用户
     * @param userCode
     * @param ActiveCode
     * @return
     */
    @Override
    public Dto AvtiveUser(String userCode, String ActiveCode) {
        if (isActive(userCode)) {
            return DtoUtil.getFailed("您的账号已经激活，请勿重新激活","102");
        }

        ItripUser user = itripUserMapper.selectActiveByUserCode(userCode);
        String code = "";
        try {
            code = redisTemplate.opsForValue().get("active:"+userCode).toString();
        }catch (RuntimeException e){
            DtoUtil.getFailed("激活失败！","107");
        }

        if (!code.equals(ActiveCode)){
           return DtoUtil.getFailed("激活码不正确！","106");
        }else {
            user.setActivated(1);
            if (itripUserMapper.updateByPrimaryKeySelective(user) < 1){
              return   DtoUtil.getFailed("激活失败！","107");
            }
        }

        return DtoUtil.getSuccess("激活成功！");
    }




    /**
     * 判断是否激活
     * @return
     */
    public boolean isActive(String userCode){

        if(isRegist(userCode)){
            ItripUser user = itripUserMapper.selectActiveByUserCode(userCode);
            if (user.getActivated() == 1) {
                return true;
            }
            return false;
        }else {
            return false;
        }

        }

    }








